/*
 * @Author: Neko
 * @Date: 2021-05-20 11:06:03
 * @LastEditTime: 2021-06-21 13:28:16
 * @LastEditors: Neko
 */
import {
	baseUrl
} from '@/config'
import storage from '@/util/storage'
import store from '@/store'

const baseURL = baseUrl()

function request(url, data, method = 'get') {
	const languageKey = storage.get('language') || uni.getSystemInfoSync().language
	const token = storage.get('token')
	const header = {
		'content-type': 'application/json',
		'Authorization': token || '',
		'Local-Language': languageKey,
		
		// #ifdef H5
		'Source-Type': 'H5',
		// #endif

		// #ifdef APP-PLUS
		'Source-Type': 'APP'
		// #endif
	}

	for (let key in data) {
		if (data[key] === null || data[key] === undefined || data[key] === 'null' || data[key] === 'undefined') {
			delete data[key]
		}
	}
	return new Promise((resolve, reject) => {
		store.commit('SET_LOADING')
		uni.request({
			url: baseURL + url,
			data,
			method,
			header,
			success: res => {
				store.commit('SET_LOADING', false)
				store.commit('SET_NET_OVER', false)
				getInToken(res.header)
				if (res.statusCode === 200) {
					const result = res.data
					if (result.code === 400) {
						if (token) {
							storage.remove('token')
						}
						// token过期更新登录状态
						store.commit('SET_LOGIN_STATE')
						uni.navigateTo({
							url: '/pages/user/login/index'
						});
						return
					}
					resolve(result)
				} else {
					uni.showToast({
						icon: 'none',
						title: '服务器错误请联系管理员:' + res.statusCode,
						duration: 1500
					});
				}
			},
			fail: err => {
				store.commit('SET_LOADING', false)
				store.commit('SET_NET_OVER', true)
				reject(err)
			}
		})
	})
}

function getInToken(res) {
	const token = res.authorization || res.Authorization
	if (token) {
		storage.set('token', token)
	}
}

export default request;
